#include "widget.h"
#include "ui_widget.h"
#include <QDebug>

Widget::Widget(QWidget *parent):QWidget(parent),ui(new Ui::Widget)//构造函数实现初始化
{   
    ui->setupUi(this);
    setWindowTitle("Client");//打印

    Clien_socket = new QTcpSocket();
}

//信号：客户端申请连接成功 槽函数：允许写入数据
void Widget::connected_SLOT()
{
    connect(Clien_socket,SIGNAL(readyRead()),this,SLOT(readyRead_SLOT()));//如果socket中有缓存消息，触发槽函数
}

//接收消息并显示到接收框
void Widget::readyRead_SLOT()
{
//      qDebug() << "Client Received!";
//      QByteArray imageData;
//      //char*buff;
//      QImage image;  //传输图片一般用QImage格式，能保证图片的完整性
//      imageData.append((QByteArray)Clien_socket->readAll());//追加数据

//      //buff=imageData.data();
//      image.loadFromData(imageData,"JPG");//把字数组的内容整合，转化为图片QImage形式
//      qDebug() << imageData.size();
//      ui->label->setPixmap(QPixmap::fromImage(image)); //把图片转化为QPixmap格式显示在lable上

 //======测试========//
//      static long long currentTime;
//      static long long lastcurrentTime;
      Frame_Buffer framebuf,bufData;
      temp_array = Clien_socket->readAll();
      if(temp_array.contains("size="))
      {
          Recv_Length = temp_array.split('=')[1].toInt();//分割为数组取[1]中的数据并转换数据
          qDebug()<<"Recv_Length data :"<<Recv_Length;
          Clien_socket->write("ack!");
          Clien_socket->waitForBytesWritten();
      }
      else
      {
          Img_Data.append(temp_array);
          qDebug()<<"step 2 : recv img data~";
          qDebug()<<"step 2 : now length = "<<Recv_Length;
          
          if(Img_Data.length()==Recv_Length)
          {
            qDebug()<<"step 3 : recv img finsh!";
            qDebug()<<"step 3 : Img_Data = "<<Img_Data.length();
            QImage bmpBuf;
            bmpBuf.loadFromData(Img_Data,"JPG");
            ui->label->setPixmap(QPixmap::fromImage(bmpBuf));

            // ui->label->setPixmap(QPixmap::fromImage(img));
            Img_Data.clear();
          }
      }

}


void Widget::on_push_open_clicked()             //连接服务器打开按键触发连接服务器
{
    Clien_socket->connectToHost(IP,Port);       //服务器地址与端口

    if(!Clien_socket->waitForConnected(1000))   //如果等待超过1000ms
    {
        qDebug("Connect failed, please try again later!\n"); //连接失败，再次点击则重新连接，将checked恢复为true
        return;
    }
   // qDebug("Connect Successfully! Connect with IP and port is: s% d%\n",IP,Port);
    connect(Clien_socket,SIGNAL(connected()),this,SLOT(connected_SLOT()));//信号：客户端申请连接成功 槽函数：允许写入数据
    connected_SLOT();
}

//断开连接
void Widget::on_push_close_clicked()
{
    qDebug() << "Disconnect!";
    //断开连接
    Clien_socket->disconnectFromHost();
    //修改按键文字&发送键静默
}

void Widget::on_push_open_2_clicked()
{
    Senddata_SLOT();
    connected_SLOT();
}

//发送消息，写入socket缓存区
void Widget::Senddata_SLOT()
{
    qDebug("Client Send: ");
    //将输入框的内容写入socket缓冲区
    Clien_socket->write("open");
    //刷新socket缓冲区
    Clien_socket->flush();
}

void Widget::yuv_to_rgb(unsigned char *yuv, unsigned char *rgb){ //格式转换
    unsigned int i;
    unsigned char* y0 = yuv + 0;
    unsigned char* u0 = yuv + 1;
    unsigned char* y1 = yuv + 2;
    unsigned char* v0 = yuv + 3;

    unsigned  char* r0 = rgb + 0;
    unsigned  char* g0 = rgb + 1;
    unsigned  char* b0 = rgb + 2;
    unsigned  char* r1 = rgb + 3;
    unsigned  char* g1 = rgb + 4;
    unsigned  char* b1 = rgb + 5;

    float rt0 = 0, gt0 = 0, bt0 = 0, rt1 = 0, gt1 = 0, bt1 = 0;

    for(i = 0; i <= (video_width * video_height) / 2 ;i++)
    {
        bt0 = 1.164 * (*y0 - 16) + 2.018 * (*u0 - 128);
        gt0 = 1.164 * (*y0 - 16) - 0.813 * (*v0 - 128) - 0.394 * (*u0 - 128);
        rt0 = 1.164 * (*y0 - 16) + 1.596 * (*v0 - 128);

        bt1 = 1.164 * (*y1 - 16) + 2.018 * (*u0 - 128);
        gt1 = 1.164 * (*y1 - 16) - 0.813 * (*v0 - 128) - 0.394 * (*u0 - 128);
        rt1 = 1.164 * (*y1 - 16) + 1.596 * (*v0 - 128);


        if(rt0 > 250)      rt0 = 255;
        if(rt0< 0)        rt0 = 0;

        if(gt0 > 250)     gt0 = 255;
        if(gt0 < 0)    gt0 = 0;

        if(bt0 > 250)    bt0 = 255;
        if(bt0 < 0)    bt0 = 0;

        if(rt1 > 250)    rt1 = 255;
        if(rt1 < 0)    rt1 = 0;

        if(gt1 > 250)    gt1 = 255;
        if(gt1 < 0)    gt1 = 0;

        if(bt1 > 250)    bt1 = 255;
        if(bt1 < 0)    bt1 = 0;

        *r0 = (unsigned char)rt0;
        *g0 = (unsigned char)gt0;
        *b0 = (unsigned char)bt0;

        *r1 = (unsigned char)rt1;
        *g1 = (unsigned char)gt1;
        *b1 = (unsigned char)bt1;

        yuv = yuv + 4;
        rgb = rgb + 6;
        if(yuv == NULL)
            break;

        y0 = yuv;
        u0 = yuv + 1;
        y1 = yuv + 2;
        v0 = yuv + 3;

        r0 = rgb + 0;
        g0 = rgb + 1;
        b0 = rgb + 2;
        r1 = rgb + 3;
        g1 = rgb + 4;
        b1 = rgb + 5;
    }
}

Widget::~Widget()
{
    delete ui;
}

//void Widget::on_push_close_clicked()
//{
//    QByteArray datagram = "above";
//    UdpClient->writeDatagram(datagram.data(), datagram.size(),QHostAddress(ipdata),1900);//
//}



//    UdpClient = new QUdpSocket(this);
//    udpClient->bind(QHostAddress(ip), QUdpSocket::ShareAddress);
//     udpClient->bind(8888); //绑定服务端的端口
//     connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(send()));
//    ipdata="172.19.233.43";
//void Widget::on_push_open_clicked()
//{
//    QByteArray datagram = "above";
//    UdpClient->writeDatagram(datagram.data(), datagram.size(),QHostAddress(ipdata),1900);//向54321端口写数据
//    qDebug("My name is xxx, nice to meet you!\n");
//}


